/*
 * @Author: lyx 2858535420@qq.com
 * @Date: 2023-04-28 10:59:59
 * @LastEditors: lyx 2858535420@qq.com
 * @LastEditTime: 2023-04-28 14:09:24
 * @FilePath: /antd-vue2-template/src/core/theme-setting.js
 * @Description: 切换主题用，改变主题色用
 */

import client from 'webpack-theme-color-replacer/client';
import generate from '@ant-design/colors/lib/generate';
import message from 'ant-design-vue/es/message';

function getAntdSerials(color) {
  // 淡化（即less的tint）
  const lightens = new Array(9).fill().map((t, i) => {
    return client.varyColor.lighten(color, i / 10);
  });
  // colorPalette变换得到颜色值
  const colorPalettes = generate(color);
  const rgb = client.varyColor.toNum3(color.replace('#', '')).join(',');
  return lightens.concat(colorPalettes).concat(rgb);
}

function changeColor(newColor) {
  var options = {
    newColors: getAntdSerials(newColor), // new colors array, one-to-one corresponde with `matchColors`
    changeUrl(cssUrl) {
      return `/${cssUrl}`; // while router is not `hash` mode, it needs absolute path
    }
  };

  return client.changer.changeColor(options, Promise);
}

/**
 * @description: 切换主题
 * @param {*} theme
 * @return {*}
 */
export function updateTheme(theme) {
  window.document.documentElement.setAttribute('data-theme', theme);
}

/**
 * @description: 切换主题色
 * @param {*} newPrimaryColor
 * @return {*}
 */
export function updateThemeColor(newPrimaryColor) {
  const hideMessage = message.loading('正在切换主题！', 0);

  changeColor(newPrimaryColor).finally(() => {
    setTimeout(() => {
      hideMessage();
    }, 10);
  });
};

/**
 * @description: 切换主题配置信息
 * @param {*} config
 * @return {*}
 */
export function updateThemeConfig(config) {
  window.less.modifyVars(config);
}

/**
 * @description: 切换弱色
 * @param {*} colorWeak
 * @return {*}
 */
export function updateColorWeak(colorWeak) {
  // document.body.className = colorWeak ? 'colorWeak' : '';
  const app = document.body.querySelector('#app');
  colorWeak ? app.classList.add('colorWeak') : app.classList.remove('colorWeak');
};
